<template>
  <div>
    <v-panel-top>
      <!--<el-button type="primary" @click="showCustomerService">新建客服</el-button>-->
      <!--<el-button type="primary" @click="showChannel">渠道商</el-button>-->
      <!--<el-button type="primary" @click="showSalesman">业务员</el-button>-->
      <el-dropdown @command="createUser">
        <el-button type="primary">
          新建用户<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item :command="{roleType:2}">客服</el-dropdown-item>
          <el-dropdown-item :command="{roleType:3}">渠道专员</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </v-panel-top>
    <v-plain-table :native="{stripe:true}" :data="users" @change="change">
      <template slot="expand" slot-scope="{scope}">
        <el-button type="text" @click="showUserDetail(scope.row)">详情</el-button>
        <el-button type="text" @click="removeUser(scope.row)" v-if="scope.row.roleType ===2 || scope.row.roleType ===3">
          删除
        </el-button>
        <el-button type="text" @click="showUserUpdate(scope.row)"
                   v-if="scope.row.roleType ===2||scope.row.roleType ===3">编辑
        </el-button>
      </template>
    </v-plain-table>
    <v-plain-form
      ref="form-append-customer-service"
      title="新建客服"
      confirmText="添加"
      :form="formCustomerService"
      :rules="rulesCustomerService"
      @confirm="confirmCustomerService"
    ></v-plain-form>
    <v-plain-form
      ref="form-update-customer-service"
      title="修改客服"
      confirmText="修改"
      :form="formCustomerService"
      :rules="rulesCustomerService"
      @confirm="updateUser"
    ></v-plain-form>
    <v-plain-form
      ref="form-append-salesman"
      title="新建渠道专员"
      confirmText="添加"
      :form="formSalesman"
      :rules="rulesSalesman"
      @confirm="confirmSalesman"
    >
      <template slot-scope="{form}" slot="expand">
        <el-form-item :label="form.profitRatio.label" prop="profitRatio.value">
          掌柜利润 X
          <el-input-number
            size="mini"
            v-model="form.profitRatio.value"
            :precision="0"
            :step="1"
            :min="0"
            :controls="false"
            :max="100"/>
          %
        </el-form-item>
      </template>
    </v-plain-form>
    <v-plain-form
      ref="form-update-salesman"
      title="修改渠道专员"
      confirmText="修改"
      :form="formSalesman"
      :rules="rulesSalesman"
      @confirm="updateUser"
    >
      <template slot-scope="{form}" slot="expand">
        <el-form-item :label="form.profitRatio.label" prop="profitRatio.value">
          掌柜利润 X
          <el-input-number
            size="mini"
            v-model="form.profitRatio.value"
            :precision="0"
            :step="1"
            :min="0"
            :controls="false"
            :max="100"/>
          %
        </el-form-item>
      </template>
    </v-plain-form>

    <v-plain-dialog
      ref="user-detail"
      title="用户详情">
      <v-form-preview
        ref="form-preview"
      />
    </v-plain-dialog>
  </div>
</template>

<script lang="ts">
  import { Vue, Component } from 'vue-property-decorator'
  import vPanelTop from '@/components/pannel-top'
  import vPlainTable from '@/components/plain-table'
  import vPlainForm from '@/components/plain-form'
  import vPlainDialog from '@/components/plain-dialog'
  import vFormPreview from '@/components/form-preview'
  import md5 from 'md5'

  @Component({
    components: {
      vPanelTop,
      vPlainTable,
      vPlainForm,
      vPlainDialog,
      vFormPreview
    }
  })
  export default class User extends Vue {
    users: TableData = {
      header: [
        {
          label: '账号',
          key: 'username'
        },
        {
          label: '姓名',
          key: 'realName'
        },
        {
          label: '角色类型',
          key: 'roleName'
        },
        {
          label: '联系方式',
          key: 'contactInformation'
        },
        {
          label: '创建日期',
          key: 'date',
          formatter: row => this.$utils.toTimeFormat(row.createTime)
        }
      ],
      body: [],
      footer: {
        total: 0,
        currentPage: 1
      }
    }
    formCustomerService = {
      realName: {
        value: '',
        label: '姓名',
        placeholder: '请输入姓名',
        type: 'input'
      },
      contactInformation: {
        value: '',
        label: '联系方式',
        placeholder: '请输入联系方式',
        type: 'input',
        maxlength: 11
      },
      username: {
        value: '',
        label: '账号',
        placeholder: '请输入账号',
        type: 'input'
      },
      password: {
        value: '',
        label: '密码',
        placeholder: '请输入密码',
        type: 'input'
      }
    }
    rulesCustomerService = {
      'realName.value': [
        {required: true, message: '请输入姓名', trigger: 'change'}
      ],
      'username.value': [
        {required: true, message: '请输入账号', trigger: 'change'},
        {min: 6, message: '账号名称不得少于6个字符', trigger: 'blur'}
      ],
      'contactInformation.value': [
        {required: true, message: '请输入联系方式', trigger: 'change'},
        {
          pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
          message: '手机号码错误',
          trigger: 'blur'
        }
      ],
      'password.value': [
        {required: true, message: '请输入密码', trigger: 'change'},
        {min: 6, message: '密码不得少于6个字符', trigger: 'blur'},
        {max: 20, message: '密码不得多于20个字符', trigger: 'blur'}
      ]
    }

    formSalesman = {
      realName: {
        value: '',
        label: '姓名',
        placeholder: '请输入姓名',
        type: 'input'
      },
      contactInformation: {
        value: '',
        label: '联系方式',
        placeholder: '请输入联系方式',
        type: 'input',
        maxlength: 11
      },
      profitRatio: {
        value: '',
        label: '利润配比',
        placeholder: '',
        type: 'chore'
      },
      username: {
        value: '',
        label: '账号',
        placeholder: '请输入账号',
        type: 'input'
      },
      password: {
        value: '',
        label: '密码',
        placeholder: '请输入密码',
        type: 'input'
      }
    }
    rulesSalesman = {
      'realName.value': [
        {required: true, message: '请输入姓名', trigger: 'change'}
      ],
      'username.value': [
        {required: true, message: '请输入姓名', trigger: 'change'}
      ],
      'contactInformation.value': [
        {required: true, message: '请输入联系方式', trigger: 'change'}
      ],
      'profitRatio.value': [
        {required: true, message: '请输入利润配比', trigger: 'change'}
      ],
      'contactInformation.value': [
        {required: true, message: '请输入联系方式', trigger: 'change'},
        {
          pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
          message: '手机号码错误',
          trigger: 'blur'
        }
      ],
      'password.value': [
        {required: true, message: '请输入密码', trigger: 'change'},
        {min: 6, message: '密码不得少于6个字符', trigger: 'blur'},
        {max: 20, message: '密码不得多于20个字符', trigger: 'blur'}
      ]
    }

    formChannel = {
      realName: {
        value: '',
        label: '渠道商名称',
        placeholder: '请输入渠道商名称',
        type: 'input'
      },
      contactInformation: {
        value: '',
        label: '联系方式',
        placeholder: '请输入联系方式',
        type: 'input'
      },
      address: {
        value: '',
        label: '详细地址',
        placeholder: '请输入详细地址',
        type: 'input'
      },
      profitRatio: {
        value: '',
        label: '利润配比',
        placeholder: '',
        type: 'chore'
      },
      salesman: {
        value: '',
        label: '渠道专员',
        placeholder: '',
        type: 'select',
        options: [
          {
            value: '/system',
            label: '系统管理'
          },
          {
            value: '/role',
            label: '角色管理'
          }
        ]
      },
      companyType: {
        value: '',
        label: '企业类型',
        placeholder: '',
        type: 'select',
        options: [
          {
            value: '/system',
            label: '系统管理'
          },
          {
            value: '/role',
            label: '角色管理'
          }
        ]
      },
      unitType: {
        value: '',
        label: '行业类型',
        placeholder: '',
        type: 'select',
        options: [
          {
            value: '/system',
            label: '系统管理'
          },
          {
            value: '/role',
            label: '角色管理'
          }
        ]
      }
    }
    rulesChannel = {
      'realName.value': [
        {required: true, message: '请输入姓名', trigger: 'change'}
      ],
      'contactInformation.value': [
        {required: true, message: '请输入联系方式', trigger: 'change'}
      ],
      'address.value': [
        {required: true, message: '请输入联系方式', trigger: 'change'}
      ],
      'profitRatio.value': [
        {required: true, message: '请输入利润配比', trigger: 'change'}
      ],
      'salesman.value': [
        {required: true, message: '请选择渠道专员', trigger: 'change'}
      ],
      'companyType.value': [
        {required: true, message: '请选择企业类型', trigger: 'change'}
      ],
      'unitType.value': [
        {required: true, message: '请选择行业类型', trigger: 'change'}
      ]
    }

    change (page) {
      this.users.footer.currentPage = page
      this.getUsers()
    }

    createUser (key) {
      switch (key.roleType) {
        case 2:
          this.showCustomerService(key.roleType)
          return
        default:
          this.showSalesman(key.roleType)
          return
      }
    }

    showCustomerService (roleType) {
      this.$refs['form-append-customer-service'].openDialog({
        roleType,
        realName: '',
        contactInformation: ''
      })
    }

    showSalesman (roleType) {
      this.$refs['form-append-salesman'].openDialog({
        roleType,
        realName: '',
        contactInformation: '',
        cardId: '',
        profitRatio: 0
      })
    }

    showUserUpdate (row) {
      if (row.roleType === 2) {
        this.$refs['form-update-customer-service'].openDialog({
          id: row.id,
          realName: row.realName,
          contactInformation: row.contactInformation,
          username: row.username,
          password: ''
        })
      } else {
        this.$refs['form-update-salesman'].openDialog({
          id: row.id,
          realName: row.realName,
          contactInformation: row.contactInformation,
          username: row.username,
          password: '',
          profitRatio: row.profitRatio
        })
      }

    }

    async showUserDetail ({id}) {
      let detail = await this.getUserDetail(id)
      let map = {
        id: '用户id',
        realName: '姓名',
        username: '账号',
        contactInformation: '联系方式',
        roleName: '角色名称'
      }
      this.$refs['user-detail'].openDialog()
      this.$nextTick(() => {
        this.$refs['form-preview'].initForm(detail, map)
      })
    }

    async confirmCustomerService (form) {
      let postData = {
        ...form,
        password: md5(form.password).toLocaleUpperCase()
      }
      let res = await  this.$axios.post('b/boms/user/customerservice/add', postData)
      this.getUsers()
      this.$utils.tips(res)
    }

    async confirmSalesman (form) {
      let postData = {
        ...form,
        password: md5(form.password).toLocaleUpperCase()
      }
      let res = await  this.$axios.post('b/boms/user/channel/add', postData)
      this.getUsers()
      this.$utils.tips(res)
    }

    async getUsers () {
      let res: AjaxResponse = await this.$axios.post('b/boms/user/users', {
        pageSize: 10,
        currentPage: this.users.footer.currentPage
      })
      this.users.body = res.data.items
      this.users.footer.total = res.data.totalNum
      this.users.footer.currentPage = res.data.currentPage
    }

    async removeUser ({id}) {
      try {
        await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res: AjaxResponse = await this.$axios.delete(`b/boms/user/delete/${id}`)
        this.getUsers()
        this.$utils.tips(res)
      } catch (e) {

      }
    }

    async getUserDetail (id) {
      let res: AjaxResponse = await this.$axios.get(`b/boms/user/view/${id}`)
      return res.data
    }

    async updateUser (form) {
      let postData = {
        ...form,
        password: md5(form.password).toLocaleUpperCase()
      }
      let res: AjaxResponse = await  this.$axios.put('b/boms/user/update', postData)
      this.$utils.tips(res)
      this.getUsers()
    }

    mounted () {
      this.getUsers()
    }
  }

</script>

<style lang="less" scoped>
  .el-input-number {
    width: 100px;
  }
</style>
